﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Shell;
using System.Windows.Threading;
using Gma.UserActivityMonitor;
using Microsoft.Shell;
using Morphine.Base;
using Morphine.Media;
using WMPLib;
using Application = System.Windows.Application;

namespace Morphine
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application, ISingleInstanceApp
    {
        public static Settings Settings;
        public static string Path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

        public static WMPLib.WindowsMediaPlayer MediaPlayer;

        public static DispatcherTimer MediaProgressTimer;

        private const string Unique = "Morphine";

        [STAThread]
        public static void Main()
        {
            if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
            {
                var application = new App();

                application.InitializeComponent();
                application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance<App>.Cleanup();
            }
        }

        private void ApplicationStartup(object sender, StartupEventArgs e)
        {
            Settings = (Settings)XmlSerializable.Load(typeof(Settings), Path + "\\settings.config") ?? new Settings();

            MediaPlayer = new WindowsMediaPlayer();

            HookManager.KeyDown += HookManagerKeyDown;

            MediaProgressTimer = new DispatcherTimer();
            MediaProgressTimer.Interval = TimeSpan.FromMilliseconds(500);

            foreach (var arg in e.Args)
            {
                if (File.Exists(arg))
                {
                    var media = App.MediaPlayer.newMedia(arg);
                    App.MediaPlayer.currentPlaylist.appendItem(media);

                    App.MediaPlayer.controls.play();
                }
            }

            if (Settings.Shuffle)
                MediaPlayer.settings.setMode("shuffle", true);

            if (Settings.IsMinimode)
                this.StartupUri = new Uri("MiniModeWindow.xaml", UriKind.Relative);

            var jumpList = new JumpList();
            JumpList.SetJumpList(this, jumpList);

            var jumpTask = new JumpTask();
            jumpTask.Title = "Play previous list";
            jumpTask.ApplicationPath = App.Path + "\\Morphine.exe";
            jumpTask.Arguments = "/resume";
            jumpTask.IconResourcePath = App.Path + "\\icon.ico";
            jumpTask.IconResourceIndex = 0;
            jumpList.JumpItems.Add(jumpTask);

            jumpList.Apply();
        }

        void HookManagerKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.MediaPlayPause:
                    if (MediaPlayer.playState == WMPPlayState.wmppsPlaying)
                        MediaPlayer.controls.pause();
                    else
                        MediaPlayer.controls.play();
                    break;
                case Keys.MediaNextTrack:
                    MediaPlayer.controls.next();
                    break;
                case Keys.MediaPreviousTrack:
                    MediaPlayer.controls.previous();
                    break;
                case Keys.MediaStop:
                    MediaPlayer.controls.stop();
                    break;
            }
        }

        private void ApplicationExit(object sender, ExitEventArgs e)
        {
            HookManager.KeyDown -= HookManagerKeyDown;

            Settings.Save(Path + "\\settings.config");
        }

        public bool SignalExternalCommandLineArgs(IList<string> args)
        {
            if (args.Count > 1)
            {
                if (args.Contains("/resume"))
                {

                    if (!File.Exists(App.Path + "\\lastplaylist"))
                        return true;
                    var list = Playlist.Read(App.Path + "\\lastplaylist");

                    MediaPlayer.currentPlaylist.clear();

                    foreach (var item in list)
                    {
                        var media = MediaPlayer.newMedia(item.File);
                        MediaPlayer.currentPlaylist.appendItem(media);
                    }

                    MediaPlayer.controls.play();
                    return true;
                }

                for (var i = 1; i < args.Count; i++)
                {
                    if (File.Exists(args[i]))
                    {
                        var media = MediaPlayer.newMedia(args[i]);
                        MediaPlayer.currentPlaylist.appendItem(media);

                        MediaPlayer.controls.play();
                    }
                }
            }
            return true;
        }
    }
}
